package com.animerank.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.animerank.entity.Anime;
import com.animerank.entity.Vote;
import com.animerank.mapper.VoteMapper;
import com.animerank.service.IAnimeService;
import com.animerank.service.IUserActivityService;
import com.animerank.service.IVoteService;
import com.animerank.dto.VoteDTO;
import com.animerank.dto.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 投票服务实现类
 */
@Service
public class VoteServiceImpl extends ServiceImpl<VoteMapper, Vote> implements IVoteService {

    @Autowired
    private VoteMapper voteMapper;

    @Autowired
    private IAnimeService animeService;
    
    @Autowired
    private IUserActivityService userActivityService;

    @Value("${anime-rank.vote.daily-limit-per-user}")
    private Integer dailyLimitPerUser;

    @Value("${anime-rank.vote.daily-limit-per-ip}")
    private Integer dailyLimitPerIp;

    @Override
    public Result<?> vote(VoteDTO voteDTO, String ip) {
        // 检查是否登录
        if (!StpUtil.isLogin()) {
            return Result.fail(401, "请先登录");
        }

        // 获取当前登录用户ID
        Long userId = StpUtil.getLoginIdAsLong();
        Long animeId = voteDTO.getAnimeId();

        // 检查用户是否已投过票
//        Integer voteCount = voteMapper.checkUserVote(userId, animeId);
//        if (voteCount != null && voteCount > 0) {
//            return Result.fail("您已经投过票了");
//        }

        // 获取今日开始时间
        LocalDateTime today = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);

        // 检查用户今日投票次数是否超过限制
        Integer userTodayVotes = voteMapper.countUserTodayVotes(userId, today);
        if (userTodayVotes != null && userTodayVotes >= dailyLimitPerUser) {
            return Result.fail("今日投票次数已达上限");
        }

        // 检查IP今日投票次数是否超过限制
        Integer ipTodayVotes = voteMapper.countIpTodayVotes(ip, today);
        if (ipTodayVotes != null && ipTodayVotes >= dailyLimitPerIp) {
            return Result.fail("当前IP今日投票次数已达上限");
        }

        // 创建投票记录
        Vote vote = new Vote();
        vote.setUserId(userId);
        vote.setAnimeId(animeId);
        vote.setVotedAt(LocalDateTime.now());
        vote.setIp(ip);

        // 保存投票记录
        voteMapper.insert(vote);
        
        // 获取动漫信息
        Anime anime = animeService.getById(animeId);
        if (anime != null) {
            // 记录用户活动
            userActivityService.recordActivity(userId, "vote", animeId, anime.getTitle(), ip);
        }
        
        return Result.success("投票成功");
    }

    @Override
    public Result<Integer> getAnimeVoteCount(Long animeId) {
        if (animeId == null) {
            return Result.fail("动漫ID不能为空");
        }

        // 查询动漫总票数
        Integer voteCount = voteMapper.countAnimeVotes(animeId);
        return Result.success(voteCount != null ? voteCount : 0);
    }
    
    @Override
    public Result<Map<String, Object>> getUserVoteHistory(Integer page, Integer pageSize) {
        // 检查是否登录
        if (!StpUtil.isLogin()) {
            return Result.fail(401, "请先登录");
        }
        
        // 获取当前登录用户ID
        Long userId = StpUtil.getLoginIdAsLong();
        
        // 计算偏移量
        int offset = (page - 1) * pageSize;
        List<Vote> votes = voteMapper.getUserVotes(userId, offset, pageSize);
        int total = voteMapper.countUserVotes(userId);
        
        // 转换为完整的动漫信息列表
        List<Anime> animeList = new ArrayList<>();
        for (Vote vote : votes) {
            // 获取动漫详情
            Result<Anime> animeResult = animeService.getAnimeDetail(vote.getAnimeId());
            if (animeResult.isSuccess() && animeResult.getData() != null) {
                Anime anime = animeResult.getData();
                // 查询实际票数
                Integer voteCount = voteMapper.countAnimeVotes(vote.getAnimeId());
                anime.setVotes(voteCount != null ? voteCount : 0);
                animeList.add(anime);
            }
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("data", animeList);
        result.put("total", total);
        
        return Result.success(result);
    }

}